<?php ob_start();?>
<?php

$root = $_SERVER ['DOCUMENT_ROOT'];
//include ($root . '/standart/head.php');
include ($root . '/standart/dateHeader.php');
include ($root . '/standart/checkUser.php');
include ($root . '/onlineOrder/ShoppingCart.class.php');
include ($root . '/onlineOrder/MenuItem.class.php');
$db = connect ();
session_start();
$type = $_GET ['type'];

function getOrder($orderId, $db, $shoppingCart){
	$categoryArray = array (
			1 => 'Çorba',
			2 => 'Ara Sıcak',
			3 => 'Ana Yemek',
			4 => 'İkram'
	);
	$stmt = "SELECT ID, USER_ID, ORDER_DATE, SHIPPING_ADDRESS, PAYMENT_TYPE, NOTES, TOTAL_AMOUNT FROM ORDERS WHERE CANCEL = 0 AND ID = ".$orderId;
	$res = $db->query ( $stmt ) or die ( $stmt . "<br/><br/>" . mysql_error () );
	if($row = $res->fetch_assoc()){
		$stmtDet = "SELECT MENU.ID AS ID, MENU.PRODUCT_NAME AS PRODUCT_NAME, FIX_MENU.CATEGORY_ID AS CATEGORY, PRICE, QUANTITY
							FROM ORDER_ITEMS, MENU LEFT JOIN FIX_MENU ON MENU.ID = FIX_MENU.MENU_ID AND FIX_MENU.MENU_DATE = DATE('".$row ['ORDER_DATE']."')
							WHERE ORDER_ITEMS.MENU_ID = MENU.ID
								AND ORDER_ID = ".$orderId;
		$resDet = $db->query ( $stmtDet ) or die ( $stmtDet . "<br/><br/>" . mysql_error () );
		while($rowDet = $resDet->fetch_assoc()){
			$resultDet[] = array(
					'ID' => $rowDet['ID'],
					'PRODUCT_NAME' => $rowDet['PRODUCT_NAME'].($rowDet['CATEGORY'] <> null ? ' | '.$categoryArray[$rowDet['CATEGORY']] : ''),
					'PRICE' => $rowDet['PRICE'],
					'QUANTITY' => $rowDet['QUANTITY']
			);
			if($shoppingCart != null){
				$shoppingCart->addItem($rowDet['ID'], $rowDet['QUANTITY'], $rowDet['PRICE']);
			}
		}
		$stmtUser = "SELECT CONCAT(CONCAT(CONCAT(GU.NAME, ' '), GU.SURNAME), CONCAT(' ', IFNULL(GEVEZE_USER.NAME, ''))) AS USERNAME
				FROM GEVEZE_USER GU LEFT JOIN GEVEZE_USER ON GU.RELATED_FIRM = GEVEZE_USER.ID
				WHERE GU.ID = ".$row ['USER_ID'];
		$resUser = $db->query ( $stmtUser ) or die ( $stmtUser . "<br/><br/>" . mysql_error () );
		if ( $rowUser = $resUser->fetch_assoc () ) {
			$userName = $row ['USER_ID'] . ' - ' . $rowUser['USERNAME'];
		}
		$result[] = array(
				'ID' => $row ['ID'],
				'USER_ID' => $row ['USER_ID'],
				'USER_NAME' => $userName,
				'ORDER_DATE' => date("d/m/Y",strtotime($row ['ORDER_DATE'])),
				'ORDER_TIME' => date("H:i",strtotime($row ['ORDER_DATE'])),
				'SHIPPING_ADDRESS' => $row ['SHIPPING_ADDRESS'],
				'TOTAL' => $row ['TOTAL_AMOUNT'],
				'PAYMENT_TYPE' => $row ['PAYMENT_TYPE'],
				'NOTES' => $row ['NOTES'],
				'DETAIL' => $resultDet
		);
		return $result;
	}
	
}

if ($type == 'name') {
	$stmt = "SELECT GU.ID, CONCAT(CONCAT(CONCAT(GU.NAME, ' '), GU.SURNAME), CONCAT(' ', IFNULL(GEVEZE_USER.NAME, ''))) AS USERNAME
				FROM GEVEZE_USER GU LEFT JOIN GEVEZE_USER ON GU.RELATED_FIRM = GEVEZE_USER.ID
				WHERE GU.NAME LIKE '%" . $_REQUEST ['term'] . "%' OR GU.SURNAME LIKE '%" . $_REQUEST ['term'] . "%' OR GEVEZE_USER.NAME LIKE '%" . $_REQUEST ['term'] . "%'";
	$res = $db->query ( $stmt ) or die ( $stmt . "<br/><br/>" . mysql_error () );
	while ( $row = $res->fetch_assoc () ) {
		$results [] = array (
				'label' => $row ['ID'] . ' - ' . $row ['USERNAME'] 
		);
	}
	echo json_encode ( $results );
	$res->close ();
} else if ($type == 'paySth') {
	$stmt = "INSERT INTO PAYMENT (USER_ID, AMOUNT, PAYMENT_TYPE) VALUES (?,?,?)";
	$statement = $db->prepare ( $stmt );
	$statement->bind_param ( 'ids', $_GET ['user_id'], $_GET ['amount'], $_GET ['payment'] );
	if ($statement->execute ()) {
		echo 'success';
	} else {
		echo 'error';
	}
	$statement->close();
} else if ($type == 'setOrder') {
	$userId = ($_GET ['user_id'] == '' ? null : $_GET ['user_id']);
	$orderType = $_GET ['order_pType'];
	$address = ($_GET ['shipping_address'] == '' ? null : $_GET ['shipping_address']);
	$applicable = $_GET ["order_date"];
	$note = $_GET ["product_note"];
	list ( $gun, $ay, $yil ) = explode ( '/', $applicable );
	$yeni_tarih = $yil . '-' . $ay . '-' . $gun . ' ' . $_GET ['order_time'];
	$shoppingCart = new Shopping_Cart('adminCart');
	$totalAmount = $shoppingCart->getTotalAmount();
	if(strtotime($yeni_tarih) < time()){
		echo 'Geçmiş tarihli siparişler üzerinde değişiklik yapamazsınız.';
		return;
	}
	if(count($shoppingCart->items) <= 0){
		echo 'Sipariş için ürün seçiniz.';
		return;
	}
	if(!isset($_GET['order_id'])){
		$stmt = "INSERT INTO ORDERS (USER_ID, ORDER_DATE, TOTAL_AMOUNT, SHIPPING_ADDRESS, PAYMENT_TYPE, NOTES) VALUES (?,?,?,?,?,?)";
		$statement = $db->prepare ( $stmt );
		$statement->bind_param ( 'isdiss', $userId, $yeni_tarih, $totalAmount, $address, $orderType, $note);
		if ($statement->execute ()) {
			$statement->close();
			$orderId = $db->insert_id;
			for($i = 0; $i < count($shoppingCart->items); $i++){
				$stmt = "INSERT INTO ORDER_ITEMS (MENU_ID, ORDER_ID, PRICE, QUANTITY) VALUES (?,?,?,?)";
				$statement = $db->prepare ( $stmt );
				$statement->bind_param ( 'iidi', $shoppingCart->items[$i]->menuId, $orderId, $shoppingCart->items[$i]->price, $shoppingCart->items[$i]->quantity);
				if (!$statement->execute ()) {
					echo 'error1';
					return;
				}
				$statement->close();
			}
			if($orderType <> 'Ödenmedi'){
				$stmt = "INSERT INTO PAYMENT (USER_ID, AMOUNT, PAYMENT_TYPE) VALUES (?,?,?)";
				$statement = $db->prepare ( $stmt );
				$statement->bind_param ( 'ids', $userId, $totalAmount, $orderType);
				if ($statement->execute ()) {
					echo 'success';
				} else {
					echo 'error2';
					return ;
				}
				$statement->close();
			}else{
				echo 'success';
			}
		} else {
			echo 'error3';
			return;
		}
		echo 'order='.$orderId;
	}else{
		$orderId = $_GET['order_id'];
		$result = getOrder($orderId, $db, null);
		if($result[0]['PAYMENT_TYPE'] <> 'Ödenmedi'){
			$stmt = "INSERT INTO PAYMENT (USER_ID, AMOUNT, PAYMENT_TYPE) VALUES (?,?,?)";
			$statement = $db->prepare ( $stmt );
			$totalMinus = ($result[0]['TOTAL'] * -1);
			$statement->bind_param ( 'ids', $result[0]['USER_ID'], $totalMinus, $result[0]['PAYMENT_TYPE']);
			if ($statement->execute ()) {
				echo 'success';
			} else {
				echo 'error2';
				return ;
			}
			$statement->close();
		}
		$stmt = "UPDATE ORDERS 
					SET USER_ID = ?, 
						ORDER_DATE = ?, 
						TOTAL_AMOUNT = ?, 
						SHIPPING_ADDRESS = ?, 
						PAYMENT_TYPE = ?, 
						NOTES = ?,
						ISPRINT = 0
					WHERE ID = ?";
		$statement = $db->prepare ( $stmt );
		$statement->bind_param ( 'isdissi', $userId, $yeni_tarih, $totalAmount, $address, $orderType, $note, $orderId);
		if ($statement->execute ()) {
			$statement->close();
			$shoppingCart = new Shopping_Cart('adminCart');
			echo 'Saved cart count '.count($shoppingCart->items);
			echo 'Saved cart count '.count($result[0]['DETAIL']).'\n';
			for($i = 0; $i < count($shoppingCart->items); $i++){
				$exists = false;
				echo 'Cart Menu = '.$shoppingCart->items[$i]->menuId;
				for($j = 0; $j < count($result[0]['DETAIL']); $j++){
					echo 'Saved Menu = '.$result[0]['DETAIL'][$j]['ID'];
					if($result[0]['DETAIL'][$j]['ID'] == $shoppingCart->items[$i]->menuId){
						$exists = true;
						unset($result[0]['DETAIL'][$j]);
						$result[0]['DETAIL'] = array_values ( $result[0]['DETAIL'] );
						echo "pop ".$j;
						break;
					}
				}
				echo '\n';
				if($exists){
					$stmt = "UPDATE ORDER_ITEMS 
								SET PRICE = ?, 
									QUANTITY = ? 
								WHERE MENU_ID = ? 
									AND ORDER_ID = ?";
					$statement = $db->prepare ( $stmt );
					$statement->bind_param ( 'diii', $shoppingCart->items[$i]->price, $shoppingCart->items[$i]->quantity, $shoppingCart->items[$i]->menuId, $orderId);
					if (!$statement->execute ()) {
						echo 'error1';
						return;
					}
					$statement->close();
				}else{
					$stmt = "INSERT INTO ORDER_ITEMS (MENU_ID, ORDER_ID, PRICE, QUANTITY) VALUES (?,?,?,?)";
					$statement = $db->prepare ( $stmt );
					$statement->bind_param ( 'iidi', $shoppingCart->items[$i]->menuId, $orderId, $shoppingCart->items[$i]->price, $shoppingCart->items[$i]->quantity);
					if (!$statement->execute ()) {
						echo 'error1';
						return;
					}
					$statement->close();
				}
			}
			for($j = 0; $j < count($result[0]['DETAIL']); $j++){
				$stmt = "DELETE FROM ORDER_ITEMS
							WHERE MENU_ID = ?
								AND ORDER_ID = ?";
				$statement = $db->prepare ( $stmt );
				echo 'Delete process with '.$result[0]['DETAIL'][$j]['ID'].' - '.$orderId;
				$statement->bind_param ( 'ii', $result[0]['DETAIL'][$j]['ID'], $orderId);
				if (!$statement->execute ()) {
					echo 'error1';
					return;
				}
				$statement->close();
			}
			if($orderType <> 'Ödenmedi'){
				$stmt = "INSERT INTO PAYMENT (USER_ID, AMOUNT, PAYMENT_TYPE) VALUES (?,?,?)";
				$statement = $db->prepare ( $stmt );
				$statement->bind_param ( 'ids', $userId, $totalAmount, $orderType);
				if ($statement->execute ()) {
					echo 'success';
				} else {
					echo 'error2';
					return ;
				}
				$statement->close();
			}else{
				echo 'success';
			}
		} else {
			echo 'error3';
			return;
		}
	}
} else if ($type == 'addCart') {
	$shoppingCart = new Shopping_Cart('adminCart');
	$shoppingCart->addItem($_GET['menu_id'], $_GET['quantity'], $_GET['price']);
} else if ($type == 'removeCart') {
	$shoppingCart = new Shopping_Cart('adminCart');
	$shoppingCart->removeItem($_GET['menu_id']);
} else if ($type == 'emptyCart') {
	$shoppingCart = new Shopping_Cart('adminCart');
	$shoppingCart->emptyCart();
} else if ($type == 'address') {
	$stmt = "SELECT ID, ADDRESS_DEFINITION FROM ADDRESS LEFT JOIN USERS_ADDRESS ON ADDRESS_ID = ADDRESS.ID WHERE USER_ID = " . $_GET ['user_id'];
	$res = $db->query ( $stmt ) or die ( $stmt . "<br/><br/>" . mysql_error () );
	?>
<option value="">Masa</option>
<?php
	while ( $row = $res->fetch_assoc () ) {
		?>
<option value="<?php echo $row['ID']; ?>"><?php echo $row['ADDRESS_DEFINITION']; ?></option>
<?php
	}
	$res->close ();
} else if ($type == 'payment') {
	$orderSum = 0;
	$paymentSum = 0;
	$stmtOrder = "SELECT SUM(TOTAL_AMOUNT) AS AMOUNT FROM ORDERS WHERE CANCEL = 0 AND USER_ID = " . $_GET ['user_id'];
	$stmtPayment = "SELECT SUM(AMOUNT) AS AMOUNT FROM PAYMENT WHERE USER_ID = " . $_GET ['user_id'];
	$resOrder = $db->query ( $stmtOrder ) or die ( $stmtOrder . "<br/><br/>" . mysql_error () );
	if ($row = $resOrder->fetch_assoc ()) {
		$orderSum = $row ['AMOUNT'];
	}
	$resOrder->close ();
	$resPayment = $db->query ( $stmtPayment ) or die ( $stmtPayment . "<br/><br/>" . mysql_error () );
	if ($row = $resPayment->fetch_assoc()) {
		$paymentSum = $row ['AMOUNT'];
	}
	$resPayment->close ();
	?>
<div class="row">
	<div class="col-lg-12">
		<div class="form-group">
			<label>Kullanıcı Adı : <?php echo $_GET['user_name'];?></label>
		</div>
	</div>
</div>
<div class="row">
	<div class="col-lg-12">
		<div class="form-group">
			<label>Toplam Borç : <?php echo number_format(($orderSum - $paymentSum), 2)." TL";?></label>
		</div>
	</div>
</div>
<div class="row">
	<div class="col-lg-12">
		<div class="form-group">
			<label>Ödeme Miktarı</label> <input class="form-control" style="text-align: right;" name="payment_amount" id="payment_amount" type="text">
		</div>
	</div>
</div>
<div class="row">
	<div class="col-lg-12">
		<div class="form-group">
			<label>Ödeme Tipi</label> 
			<select class="form-control" name="payment_type" id="payment_type">
				<option value="Nakit">Nakit</option>
				<option value="Yemek Kartı">Ticket/SetCart/Multinet</option>
				<option value="Kredi Kartı">Kredi Kartı</option>
			</select>
		</div>
	</div>
</div>
<div class="row">
	<div class="col-lg-12">
		<div class="form-group">
			<button type="button" id="setPayment" class="btn btn-default" style="float: right;" onclick="getPaymentFromUser('<?php echo number_format(($orderSum - $paymentSum), 2);?>');">Ödeme Yap</button>
		</div>
	</div>
</div>
<?php
} else if ($type == 'orderDetail') {
	if(isset($_GET['orderId'])){
		$shoppingCart = new Shopping_Cart('adminCart');
		$shoppingCart->emptyCart();
		$result = getOrder($_GET['orderId'], $db, $shoppingCart);
		echo json_encode ( $result, JSON_FORCE_OBJECT);
	}
} else if ($type == 'cancelOrder') {
	$applicable = $_GET ["order_date"];
	list ( $gun, $ay, $yil ) = explode ( '/', $applicable );
	$yeni_tarih = $yil . '-' . $ay . '-' . $gun . ' ' . $_GET ['order_time'];
	if(strtotime($yeni_tarih) < time()){
		echo 'Geçmiş tarihli siparişleri iptal edemezsiniz.';
		return;
	}
	if(isset($_GET['orderId'])){
		$shoppingCart = new Shopping_Cart('adminCart');
		$shoppingCart->emptyCart();
		$stmt = "UPDATE ORDERS
					SET ISPRINT = 0,
						CANCEL = 1
					WHERE ID = ?";
		$statement = $db->prepare ( $stmt );
		$statement->bind_param ( 'i', $_GET['orderId']);
		if ($statement->execute ()) {
			$statement->close();
			echo 'success';
		}else {
			echo 'error';
			return;
		}
	}
}
disconnect ( $db );
?>
<?php ob_end_flush(); ?>